require 'View.Base.BehaviourView'
local json = require "cjson"
AnimatorStateBindShow = class("AnimatorStateBindShow", BehaviourView)


function AnimatorStateBindShow:Awake(obj)
    BehaviourView.Awake(self, obj)
    self.animator = self.gameObject:GetComponent("Animator")
    self.bindShowInfo = nil

    self.paramList = json.decode(self.mainProperty)
end

function AnimatorStateBindShow:OnShow()
    BehaviourView.OnShow(self)
    if self.bindShowInfo==nil and self.animator.runtimeAnimatorController~=nil then
        self.bindShowInfo = {}

        local list = LuaFramework.Util.AnimatorGetBehaviours(self.animator)
        if list.Length==0 then 
            self.luaBehaviour.enabled = false
            return 
        end
        for i = 1, list.Length do
            local behaviour = list[i-1]
            behaviour.onEnter = handler(self, self.onStateEnterEvent)
            behaviour.onExit = handler(self, self.onStateExitEvent)
        end


        for _, v in ipairs(self.paramList) do
            if self.bindShowInfo[v.stateName]==nil then self.bindShowInfo[v.stateName]={} end
            table.insert(self.bindShowInfo[v.stateName], {
                stateName = v.stateName,
                prefabPath = string.substringAfter(v.prefabPath, LoadManager.rootPath.."/"),
                nodeGo = self[v.nodePropertyName] or self.gameObject
            })
        end
    end
end

function AnimatorStateBindShow:getBindShowInfo(stateInfo)
    for stateName,bindShowInfo in pairs(self.bindShowInfo) do
        if stateInfo:IsName(stateName) then
            return bindShowInfo
        end
    end
    return nil
end
function AnimatorStateBindShow:loadBindShowSync(info)
    local go = RESM.InstantiateAssetAsync(info.prefabPath)
    go.transform:SetParent(info.nodeGo.transform, false)
    info.go = go
end
function AnimatorStateBindShow:onStateEnterEvent(stateInfo)
    local bindShowInfo = self:getBindShowInfo(stateInfo)
    if bindShowInfo==nil or #bindShowInfo==0 then return end
    for _, v in ipairs(bindShowInfo) do
        if v.go~=nil then 
            v.go:SetActive(false)
            v.go:SetActive(true)
        else
            self:StartCoroutine(function()
                self:loadBindShowSync(v)
            end)
        end
    end
end
function AnimatorStateBindShow:onStateExitEvent(stateInfo)
    local bindShowInfo = self:getBindShowInfo(stateInfo)
    if bindShowInfo==nil or #bindShowInfo==0 then return end
    for _, v in ipairs(bindShowInfo) do
        if v.go~=nil then 
            --v.go:SetActive(false)
        end
    end
end